<template>
  <el-form
    ref="ruleForm"
    :model="ruleForm"
    status-icon
    label-width="100px"
    class="demo-ruleForm"
    :rules="rules"
  >
    <el-form-item label="旧密码:" prop="oldPassword">
      <el-input
        v-model="ruleForm.oldPassword"
        placeholder="请输入旧密码"
      ></el-input>
    </el-form-item>
    <el-form-item label="新密码：" prop="newPassword">
      <el-input
        v-model="ruleForm.newPassword"
        placeholder="请输入新密码"
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码：" prop="configPassword">
      <el-input
        v-model.number="ruleForm.configPassword"
        placeholder="请输入确认密码"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')" size="mini"
        >提交</el-button
      >
      <el-button type="danger" @click="close" size="mini">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateAmend } from '@/api/profile'
export default {
  data () {
    const confirmPassword = (rule, value, callback) => {
      if (this.ruleForm.newPassword !== value.toString()) {
        callback(new Error('确认密码和新密码不一致！'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        newPassword: '',
        configPassword: '',
        oldPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '旧密码不能为空！', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空！', trigger: 'blur' },
          { min: 4, max: 6, message: '长度在4~6个字符', trigger: 'blur' }
        ],
        configPassword: [
          { required: true, message: '确认密码不能为空！', trigger: 'blur' },
          { required: true, validator: confirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateAmend({
            oldPassword: this.ruleForm.oldPassword,
            password: this.ruleForm.newPassword,
            configPassword: this.ruleForm.configPassword.toString()
          }).then(this.$message.success('修改密码成功！'))
        }
      })
    },
    close () {
      this.$router.push({ path: '/home' })
    }
  }
}
</script>

<style>
</style>
